<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

use mbilling\BillingBundle\Model\DomainsModel;
use mbilling\BillingBundle\Model\DomainsStatusesModel;
use mbilling\BillingBundle\Model\OrdersModel;
use mbilling\BillingBundle\Model\UsersBillsModel;
use mbilling\BillingBundle\Model\UsersLogsModel;
use mbilling\BillingBundle\Model\DomainsZonesModel;
use mbilling\BillingBundle\Model\DomainsDnsModel;
use mbilling\BillingBundle\Entity\domains;
use mbilling\BillingBundle\Entity\usersLogs;
use mbilling\BillingBundle\Entity\usersBills;
use mbilling\BillingBundle\Entity\domainsDns;

use mbilling\BillingBundle\Form\DomainsForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;

class DomainsController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $order_model = new OrdersModel($em);
        $bill_model = new UsersBillsModel($em);
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();     
                    
        $parameters = array();
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                $domains = $domain_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $domains = $domain_model->findAll();
        }
        else
            $domains = $domain_model->findByUserId($userCurrent->getId());
        foreach($domains as $domain)
        {
            $order = $order_model->findByPK($domain->getOrderId());
            if (isset($order))
                $bill = $bill_model->findByOrderId($domain->getOrderId());
            else
            {
                $order = 0;
                $bill = 0;
            }
            array_push($parameters, array('domain' => $domain,
                                          'order'  => $order,
                                          'bill'   => $bill));
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Domains:user_index.html.twig', array('parameters' => $parameters));
            else
                return $this->render('BillingBundle:Domains:admin_index.html.twig', array('parameters' => $parameters));
        }
        else
            return $this->render('BillingBundle:Domains:user_index.html.twig', array('parameters' => $parameters));
        
    }
    public function addAction()
    {
        $order_name = '0';
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $zone_model = new DomainsZonesModel($em);

        $dir=opendir(dirName('../'.basename(__FILE__)).'/src/mbilling/BillingBundle/DomainFileTemplates/');
        $file_string = array();
        $templ_array = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $file_string[count($file_string)] = $file;
            $templ_array[$file] = array();
            $templ_file = file(dirName('../'.basename(__FILE__)).'/src/mbilling/BillingBundle/DomainFileTemplates/'.$file);
            for($i = 0; $i < count($templ_file); $i++)
            {
                $temp = explode("\t", $templ_file[$i]);
                array_push($templ_array[$file], $temp);
            }
        }
        closedir($dir);
        array_multisort($file_string);
        
        $domain = new domains();
        //$domain_model->create($domain->initDefaultEntity());//создание по умолчанию
        //return new RedirectResponse($this->generateUrl('users_bills_show'));
        if (isset($_POST['name']))
            $domain->setName($_POST['name']);
        if (isset($_POST['ns1']))
            $domain->setFirstNsServer($_POST['ns1']);
        if (isset($_POST['ns2']))
            $domain->setSecondNsServer($_POST['ns2']);
        if (isset($_POST['template']))
            $template = $_POST['template'];
        $form = $this->createForm(new DomainsForm($file_string), $domain);
        //print_r($domain);
        print_r($_POST);
        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            //$form->bindRequest($request);
            //print_r($form->getErrors());
            //if ($form->isValid())
            if ($form->isSynchronized())
            {
                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $check_domain = $this->get('check_domain');
                $check_domain->init($domain->getName());
                $zone = $zone_model->findByName($check_domain->get_tld());

                $domain->setOrderId('0');
                $domain->setZoneId($zone->getId());
                $domain->setStatusId('1');
                $domain->setIsActive('0');
                $domain->setForRemove('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $domain->setUserId($this->get('session')->get('user')->getId());
                else
                    $domain->setUserId($userCurrent->getId());
                $domain_model->create($domain);

                $acl = $this->get('acl');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($domain, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($domain, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($domain);

                $dns_model = new DomainsDnsModel($em);
                $dns1 = array();
                if ($domain->getFirstNsServer())
                {
                    $dns1['0'] = "ns1";
                    $dns1['1'] = "NS";
                    $dns1['2'] = $domain->getFirstNsServer();
                }
                $dns2 = array();
                if ($domain->getSecondNsServer())
                { 
                    $dns2['0'] = "ns2";
                    $dns2['1'] = "NS";
                    $dns2['2'] = $domain->getSecondNsServer();
                }
                array_unshift($templ_array[$template], $dns1);
                array_unshift($templ_array[$template], $dns2);
                foreach ($templ_array[$template] as $item)
                {
                    if (!isset($item['0']) || !isset($item['1']) || !isset($item['2']))
                        continue;
                    $dns = new DomainsDns();
                    $dns->setName($item['0']);
                    $dns->setType($item['1']);
                    $dns->setValue($item['2']);
                    $dns->setDomainId($domain->getId());
                    $dns->setForRemove('0');
                    $dns->setIsActive('0');
                    $dns_model->create($dns);
                }
                $bill_model = new UsersBillsModel($em);
                $bill = new usersBills();
                $bill->setMoney($zone->getRegCost());
                $bill->setIsReal('1');
                $bill->setIsPaid('0');
                $bill->setSourceId('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId('0');
                $bill->setDomainId($domain->getId());
                $bill->setType('4');
                $bill_model->create($bill);

                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('1');//создание домена
                $log->setOrderId('0');
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
        }
        return $this->render('BillingBundle:Domains:create.html.twig', array('form' => $form->createView(), 'order_name' => $order_name, 'templates' => $file_string));
    }
    public function add_to_orderAction()
    {
        $order_name = $this->get('session')->get('order');
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $zone_model = new DomainsZonesModel($em);
        $order_model = new OrdersModel($em);
        $order = $order_model->findByOrderName($order_name);
        
        $dir=opendir(dirName('../'.basename(__FILE__)).'/src/mbilling/BillingBundle/DomainFileTemplates/');
        $file_string = array();
        $templ_array = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $file_string[count($file_string)] = $file;
            $templ_array[$file] = array();
            $templ_file = file(dirName('../'.basename(__FILE__)).'/src/mbilling/BillingBundle/DomainFileTemplates/'.$file);
            for($i = 0; $i < count($templ_file); $i++)
            {
                $temp = explode("\t", $templ_file[$i]);
                array_push($templ_array[$file], $temp);
            }
        }
        closedir($dir);
        array_multisort($file_string);
        
        $domain = new domains();
        //$domain_model->create($domain->initDefaultEntity());//создание по умолчанию
        //return new RedirectResponse($this->generateUrl('users_bills_show'));
        if (isset($_POST['name']))
            $domain->setName($_POST['name']);
        if (isset($_POST['ns1']))
            $domain->setFirstNsServer($_POST['ns1']);
        if (isset($_POST['ns2']))
            $domain->setSecondNsServer($_POST['ns2']);
        if (isset($_POST['template']))
            $template = $_POST['template'];
        $form = $this->createForm(new DomainsForm, $domain);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            //$form->bindRequest($request);
            //if ($form->isValid())
            //if ($form->isSynchronized())
            {
                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $check_domain = $this->get('check_domain');
                $check_domain->init($domain->getName());
                $zone = $zone_model->findByName($check_domain->get_tld());

                $domain->setOrderId($order->getId());
                $domain->setZoneId($zone->getId());
                $domain->setStatusId('1');
                $domain->setIsActive('0');
                $domain->setForRemove('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $domain->setUserId($this->get('session')->get('user')->getId());
                else
                    $domain->setUserId($userCurrent->getId());
                $domain_model->create($domain);

                $acl = $this->get('acl');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($domain, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($domain, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($domain);

                $dns_model = new DomainsDnsModel($em);
                $dns1 = array();
                if ($domain->getFirstNsServer())
                {
                    $dns1['0'] = "ns1";
                    $dns1['1'] = "NS";
                    $dns1['2'] = $domain->getFirstNsServer();
                }
                $dns2 = array();
                if ($domain->getSecondNsServer())
                { 
                    $dns2['0'] = "ns2";
                    $dns2['1'] = "NS";
                    $dns2['2'] = $domain->getSecondNsServer();
                }
                array_unshift($templ_array[$template], $dns1);
                array_unshift($templ_array[$template], $dns2);
                foreach ($templ_array[$template] as $item)
                {
                    if (!isset($item['0']) || !isset($item['1']) || !isset($item['2']))
                        continue;
                    $dns = new DomainsDns();
                    $dns->setName($item['0']);
                    $dns->setType($item['1']);
                    $dns->setValue($item['2']);
                    $dns->setDomainId($domain->getId());
                    $dns->setForRemove('0');
                    $dns->setIsActive('0');
                    $dns_model->create($dns);
                }
                
                $bill_model = new UsersBillsModel($em);
                $bill = new usersBills();
                $bill->setMoney($zone->getRegCost());
                $bill->setIsReal('1');
                $bill->setIsPaid('0');
                $bill->setSourceId('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId($order->getId());
                $bill->setDomainId($domain->getId());
                $bill->setType('4');
                $bill_model->create($bill);

                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('6');//создание домена для заказа
                $log->setOrderId($order->getId());
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
        }
        return $this->render('BillingBundle:Domains:create.html.twig', array('form' => $form->createView(), 'order_name' => $order_name, 'templates' => $file_string));
    }
    public function removeAction()
    {
        $domain_name = $_POST['domain'];
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $domain = $domain_model->findByDomainName($domain_name);
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($domain, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($domain, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($domain, $userCurrent);
        $acl->removePermissionsForAllAdmins($domain);
        //добавить удаление счетов
        $domain_model->removeByPK($domain->getId());

        $log_model = new UsersLogsModel($em);
        $log = new usersLogs();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $log->setUserId($this->get('session')->get('user')->getId());
        else
            $log->setUserId($userCurrent->getId());
        $log->setActionTypeId('3');//удаление домена
        $log->setOrderId('0');
        $log_model->create($log);
            
        return new RedirectResponse($this->generateUrl('domains_show'));
    }
    public function showTemplateAction()
    {
        $file = $_POST['file'];
        $templ_file = file(dirName('../'.basename(__FILE__)).'/src/mbilling/BillingBundle/DomainFileTemplates/'.$file);
        $template_string = array();
        for($i = 0; $i < count($templ_file); $i++)
        {
            $temp = explode("\t", $templ_file[$i]);
            if (isset($temp['0']) && isset($temp['1']) && isset($temp['2']))
                array_push($template_string, $temp);
        }
        return $this->render('BillingBundle:Domains:template.html.twig', array('template' => $template_string));
    }
    public function change_statusAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $domain = $domain_model->findByPK($id);

        $status_model = new DomainsStatusesModel($em);
        $statuses = $status_model->findAll();
        $temp_array = array();
        foreach($statuses as $status)
        {
            $temp_array[$status->getId()] = 'name:'.$status->getName();
        }

        $form = $this->createFormBuilder($domain)
            ->add('status_id', 'choice', array('choices' => $temp_array))
            ->getForm();

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $domain_model->create($form->getData());
                return new RedirectResponse($this->generateUrl('domains_show'));
            }
        }
        return $this->render('BillingBundle:Domains:change_status.html.twig', array('form' => $form->createView()));
    }
}